# !/usr/bin/env python
# -*- coding:utf-8 -*-
# 导入PyQt6
from PyQt6.QtCore import QPoint
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QGraphicsScene, QGraphicsPixmapItem, QWidget
from view.imagemax import Ui_imagemax

# ==============================================================================
# view 11.bug图片页面
# ==============================================================================


class Image_bug(QWidget, Ui_imagemax):
    """大图片页面"""
    _instance = None

    def __new__(cls, str_encode, parent=None):
        if cls._instance is None:
            instance = super().__new__(cls)
            instance.__init__(str_encode, parent)
            cls._instance = instance  # 保存到类变量以便后续使用
            return instance
        else:
            cls._instance.update_image(str_encode)  # 更新现有实例的图像数据
            return cls._instance

    def __init__(self, str_encode, parent=None):
        if self._instance:  # 避免多次初始化同一个实例
            return
        super().__init__(parent)
        self.str_encode = str_encode
        self.setupUi(self)
        self.init_image()

    def init_image(self):
        """窗口加载图片显示"""
        pixmap = QPixmap()
        pixmap.loadFromData(self.str_encode)
        scene = QGraphicsScene()            # 创建图形视图、场景及图像项目
        item = QGraphicsPixmapItem(pixmap)
        item.setFlag(QGraphicsPixmapItem.GraphicsItemFlag.ItemIsMovable)        # 设置图片项可拖动
        scene.addItem(item)
        self.graphicsView.setScene(scene)   # 设置视图与场景
        self.graphicsView.wheelEvent = self.wheelEvent_handler    # 重写滚轮事件处理函数
        self.show()

    def update_image(self, new_str_encode):
        """更新窗口图片"""
        self.str_encode = new_str_encode
        self.init_image()   # 重新加载图片数据
        self.activateWindow()  # 激活窗口
        self.raise_()       # 提升窗口至最前面

    def wheelEvent_handler(self, event):
        """滚轮放大缩小图片"""
        zoom_in_factor = 1.25
        zoom_out_factor = 1 / zoom_in_factor
        delta = event.angleDelta().y() / 120
        if delta > 0:
            factor = zoom_in_factor
        elif delta < 0:
            factor = zoom_out_factor
        else:
            return
        # 获取当前鼠标位置在视图坐标系中的位置
        mouse_pos_scene = self.graphicsView.mapToScene(QPoint(int(event.position().x()), int(event.position().y())))
        # 记录原始视图中心点
        old_center = self.graphicsView.viewport().rect().center()
        # 缩放视图
        self.graphicsView.scale(factor, factor)
        # 计算新的视图中心点，并确保鼠标下的内容不变
        new_center = self.graphicsView.mapFromScene(mouse_pos_scene).toPointF()
        self.graphicsView.centerOn(new_center)
